<template>
  <div class="head-container">
    <el-tree
      ref="treeRef"
      :data="treeData"
      :expand-on-click-node="false"
      :filter-node-method="filterNode"
      :props="defaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      @node-click="handleNodeClick"
    />
  </div>
</template>

<script setup>
defineOptions({ name: "JyzWithArea" });

import { ElTree } from "element-plus";
import { defaultProps, handleTree } from "@/utils/tree";
import { listQy } from "@/api/yqhs/qy";
import { listJyz } from "@/api/yqhs/jyz";
import { onMounted } from "vue";
import { ref } from "vue";
let treeData = ref([]);
onMounted(async () => {
  let data = [];
  let qyRes = await listQy();
  let qyRows = qyRes.data;
  for (let row of qyRows) {
    data.push({ id: row.id, parentId: row.parentId, name: row.qymc });
  }

  let jyzRes = await listJyz({ pageNum: 1, pageSize: 1000 });
  let jyzRows = jyzRes.rows;

  for (let row of jyzRows) {
    data.push({ id: row.id, parentId: row.qyId, name: row.jyzmc, leaf: true });
  }
  treeData.value = handleTree(data);
});
const treeRef = ref();

/** 基于名字过滤 */
const filterNode = (name, data) => {
  if (!name) return true;
  return data.name.includes(name);
};

/** 处理部门被点击 */
let currentNode = {};
const handleNodeClick = async (row, treeNode) => {
  // 判断选中状态
  if (currentNode && currentNode.name === row.name) {
    treeNode.checked = !treeNode.checked;
  } else {
    treeNode.checked = true;
  }
  if (treeNode.checked) {
    // 选中
    currentNode = row;
    emits("node-click", row);
  } else {
    // 取消选中
    treeRef.value.setCurrentKey(undefined);
    emits("node-click", undefined);
    currentNode = null;
  }
};
const emits = defineEmits(["node-click"]);
</script>
